import axios from 'axios'
import { Message } from 'element-ui'
// import store from '@/store'

// 封装获取 cookie 的方法
function getCookie(name){
  let arr1 = document.cookie.split('; ')
  let i = 0;
  for (i = 0; i < arr1.length; i++) {
    var arr2 = arr1[i].split('=')
    if (arr2[0] == name) {
      return arr2[1]
    }
  }
  return ''
}

const instance = axios.create({
  baseURL: '/api',
  headers: { 'Content-Type': 'application/json' }
})

const errorHandle = (status, message, url) => {
  switch (status) {
    case 401:
      // url !== '/activity/icid' && store.dispatch('logout')
      console.log(url)
      break
    case 403:
      Message.error(message)
      break
    case 404:
      break
    default:
      Message.error(message)
  }
}

instance.interceptors.request.use(
  config => {
    // config.headers.Authorization = `Bearer jianhongtest`,
    config.headers[`x-csrf-token`] =  getCookie("csrfToken") // 前后端不分离的情况加每次打开客户端，egg会直接在客户端的 Cookie 中写入密钥 ，密钥的 Key 就是 'scrfToken' 这个字段，所以直接获取就好了
    // config.headers.Authorization = `Bearer ${store.state.auth.token}`
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  response => {
    response.success = response.data.success
    if (!response.success) {
      response.data.message && Message.error(response.data.message)
    } else {
      const black = ['/activity/edit', '/visit/overview', '/visit/list', '/version/find', '/test/list', '/test/info', '/version/list', '/template/use', '/template/createLabel', '/extend/', '/combination/find', '/combination/delete', '/label/delete', 'classify/sort', 'site/test/edit', 'site/log', 'heatmap/list', '/statistics/report/overview', '/statistics/report/monitor/', '/statistics/report/error/', '/statistics/report/visit/total', '/event/query', '/activity/eventlist', '/loginSSOForOuter', '/statistics/record/query', 'visual/component/getType', 'visual/component/get', '/visual/component/list']
      black.every(x => !response.config.url.includes(x)) &&
        response.config.method === 'post' &&
        response.data.message &&
        Message.success(response.data.message)
    }
    return response
  },
  error => {
    const { response } = error
    response
      ? errorHandle(response.status, response.data.message, response.config.url)
      : Message.warning('网络连接失败，请稍后重试！')
    return Promise.reject(error)
  }
)

export const createAPI = (url, method, params, config = {}) => {
  if (method === 'get') {
    config.params = params
  } else {
    config.data = params
  }
  return instance({
    url,
    method,
    ...config
  })
}

export const createUpload = (url, params, config = {}) => {
  const objectToFormdata = (obj, form, namespace) => {
    let fd = form || new FormData()
    let formKey

    for (let property in obj) {
      try {
        // if (obj.hasOwnProperty(property)) {
        if (property) {
          let key = Array.isArray(obj) ? `[${property}]` : `.${property}`
          if (namespace) {
            formKey = namespace + key
          } else {
            formKey = property
          }
  
          if (obj[property] instanceof Date) {
            fd.append(formKey, obj[property].toISOString())
          } else if (
            typeof obj[property] === 'object' &&
            !(obj[property] instanceof File)
          ) {
            objectToFormdata(obj[property], fd, formKey)
          } else if (obj[property] !== undefined) {
            fd.append(formKey, obj[property])
          }
        }
      } catch(e) {
        console.log(e)
      }
    }

    return fd
  }

  config.data = objectToFormdata(params)
  config.headers = { 'Content-Type': 'multipart/form-data' }
  return instance({
    url,
    method: 'post',
    ...config
  })
}

export default instance
